package com.dayatang.android.Db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dayatang.android.Model.Person;

public class PersonServiceDb {
	
	private DBOpenHelper dbOpenHelper;

	public PersonServiceDb(Context context){
		this.dbOpenHelper = new DBOpenHelper(context);
	}
	
	public void save(Person person){
		
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		
		values.put("name", person.getName());
		values.put("organization_name", person.getOrganizationName());
		values.put("holderofan_office", person.getHolderofanOffice());
		values.put("cell_phone", person.getCellphone());
		
		db.insert("persons", null, values);
		db.close();
	}
	
	public List<Person> findPerson(){
		
		List<Person> persons = new ArrayList<Person>();
		
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		Cursor cursor = db.query("persons", null, null, null, null, null, null);

		while(cursor.moveToNext()){
			
			Person person = new Person();
			
			person.setName(cursor.getString(cursor.getColumnIndex("name")));
			person.setOrganizationName(cursor.getString(cursor.getColumnIndex("organization_name")));
			person.setHolderofanOffice(cursor.getString(cursor.getColumnIndex("holderofan_office")));
			person.setCellphone(cursor.getString(cursor.getColumnIndex("cell_phone")));
			
			persons.add(person);
			
		}
		
		cursor.close();
		db.close();
		
		return persons;
	}
	
	public void delAll(){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.delete("persons", null, null);
		
		db.close();
	}
	
}
